import React, { useState, useEffect } from 'react';
import { Layout, Row, Col, Typography, Space, Button, Modal, Tabs } from 'antd';
import { 
  LineChartOutlined, 
  SettingOutlined,
  ApiOutlined,
  BarChartOutlined,
  ClockCircleOutlined
} from '@ant-design/icons';
import KLineChart from './components/KLineChart';
import TimeshareChart from './components/TimeshareChart';
import WeightInput from './components/WeightInput';
import IndicatorPanel from './components/IndicatorPanel';
import { WeightAPI } from './services/api';
import './App.css';

const { Header, Content, Sider } = Layout;
const { Title, Text } = Typography;

function App() {
  const [refreshTrigger, setRefreshTrigger] = useState(0);
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
  const [connectionStatus, setConnectionStatus] = useState<'connected' | 'disconnected' | 'checking'>('checking');

  // 检查后端连接状态
  const checkConnection = async () => {
    try {
      setConnectionStatus('checking');
      await WeightAPI.healthCheck();
      setConnectionStatus('connected');
    } catch (error) {
      setConnectionStatus('disconnected');
      console.error('Backend connection failed:', error);
    }
  };

  // 刷新数据
  const handleDataRefresh = () => {
    setRefreshTrigger(prev => prev + 1);
  };

  // 组件挂载时检查连接
  useEffect(() => {
    checkConnection();
    // 每30秒检查一次连接状态
    const interval = setInterval(checkConnection, 30000);
    return () => clearInterval(interval);
  }, []);

  // 连接状态指示器
  const renderConnectionStatus = () => {
    const statusConfig = {
      connected: { color: '#52c41a', text: '已连接' },
      disconnected: { color: '#f5222d', text: '连接失败' },
      checking: { color: '#faad14', text: '检查中...' }
    };

    const config = statusConfig[connectionStatus];
    
    return (
      <Space size="small">
        <div 
          style={{
            width: 8,
            height: 8,
            borderRadius: '50%',
            backgroundColor: config.color,
            display: 'inline-block'
          }}
        />
        <Text style={{ color: config.color, fontSize: '12px' }}>
          {config.text}
        </Text>
      </Space>
    );
  };

  // 显示API连接提示
  const showConnectionInfo = () => {
    Modal.info({
      title: '连接状态',
      content: (
        <div>
          <p>后端API状态: {connectionStatus === 'connected' ? '✅ 正常' : '❌ 断开'}</p>
          <p>API地址: {process.env.REACT_APP_API_URL || 'http://localhost:3001/api'}</p>
          {connectionStatus !== 'connected' && (
            <p style={{ color: '#f5222d' }}>
              请确保后端服务已启动 (npm run dev:backend)
            </p>
          )}
        </div>
      ),
      onOk() {}
    });
  };

  return (
    <div className="App">
      <Layout style={{ minHeight: '100vh', backgroundColor: '#0a0e1b' }}>
        {/* 头部 */}
        <Header style={{ 
          backgroundColor: '#1a1a1a', 
          borderBottom: '1px solid #333',
          padding: '0 24px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between'
        }}>
          <Space size="large">
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <LineChartOutlined style={{ fontSize: '24px', color: '#00da3c', marginRight: '12px' }} />
              <Title level={3} style={{ color: '#fff', margin: 0 }}>
                📈 陈伟基减肥日记
              </Title>
            </div>
            
            <Space size="middle">
              <div style={{ color: '#00da3c', fontSize: '20px', fontWeight: 'bold' }}>
                94.4kg
              </div>
              <div style={{ color: '#ec0000', fontSize: '14px' }}>
                今日 📊 +0.5kg (1.3%)
              </div>
            </Space>
          </Space>

          <Space>
            {renderConnectionStatus()}
            <Button 
              type="text" 
              icon={<ApiOutlined />} 
              onClick={showConnectionInfo}
              style={{ color: '#999' }}
            />
            <Button 
              type="text" 
              icon={<SettingOutlined />}
              style={{ color: '#999' }}
            />
          </Space>
        </Header>

        <Layout>
          {/* 侧边栏 */}
          <Sider 
            width={320}
            collapsed={sidebarCollapsed}
            onCollapse={setSidebarCollapsed}
            className="sider"
            style={{ 
              backgroundColor: '#1a1a1a',
              borderRight: '1px solid #333'
            }}
            collapsible
            theme="dark"
          >
            <div style={{ padding: '12px' }}>
              {!sidebarCollapsed && (
                <>
                  <WeightInput 
                    onSuccess={handleDataRefresh}
                    onGenerateMockData={handleDataRefresh}
                  />
                  <div style={{ marginTop: '12px' }}>
                    <IndicatorPanel refreshTrigger={refreshTrigger} />
                  </div>
                </>
              )}
            </div>
          </Sider>

          {/* 主内容区 */}
          <Content style={{ 
            padding: '16px',
            backgroundColor: '#0a0e1b',
            overflow: 'auto',
            marginLeft: '0',
            width: '100%',
            flex: 1
          }}>
            <Row gutter={[16, 16]} style={{ width: '100%' }}>
              {/* 图表区域 */}
              <Col span={24} style={{ width: '100%' }}>
                <Tabs
                  defaultActiveKey="kline"
                  style={{ width: '100%' }}
                  items={[
                    {
                      key: 'kline',
                      label: 'K线图',
                      children: (
                        <div style={{ width: '100%', height: '100%' }}>
                          <KLineChart 
                            refreshTrigger={refreshTrigger}
                          />
                        </div>
                      )
                    },
                    {
                      key: 'timeshare',
                      label: '分时图',
                      children: (
                        <div style={{ width: '100%', height: '100%' }}>
                          <TimeshareChart />
                        </div>
                      )
                    }
                  ]}
                />
              </Col>

              {/* 底部状态栏 */}
              <Col span={24}>
                <div style={{
                  padding: '8px 16px',
                  backgroundColor: '#1a1a1a',
                  borderRadius: '4px',
                  border: '1px solid #333',
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center'
                }}>
                  <Space size="large">
                    <Text style={{ color: '#999', fontSize: '12px' }}>
                      💡 <span style={{color: '#ec0000'}}>🔴红色蜡烛</span>=体重上升需加油 | <span style={{color: '#00da3c'}}>🟢绿色蜡烛</span>=减重成功 | 
                      <span style={{color: '#f39800'}}>MA5</span> | <span style={{color: '#1890ff'}}>MA10</span> | <span style={{color: '#722ed1'}}>MA20</span> 均线指导
                    </Text>
                  </Space>
                  
                  <Space>
                    <Text style={{ color: '#999', fontSize: '12px' }}>
                      最后更新: {new Date().toLocaleString()}
                    </Text>
                    <Button 
                      type="text" 
                      size="small"
                      onClick={handleDataRefresh}
                      style={{ color: '#999' }}
                    >
                      刷新
                    </Button>
                  </Space>
                </div>
              </Col>
            </Row>
          </Content>
        </Layout>
      </Layout>

      {/* 连接断开时的提示 */}
      {connectionStatus === 'disconnected' && (
        <div style={{
          position: 'fixed',
          top: '70px',
          right: '16px',
          background: '#fff2f0',
          border: '1px solid #ffccc7',
          borderRadius: '4px',
          padding: '8px 12px',
          color: '#a8071a',
          fontSize: '12px',
          zIndex: 1000
        }}>
          ⚠️ 后端服务未连接，请启动后端服务
        </div>
      )}
    </div>
  );
}

export default App;
